package controller

import (
	"blog_server/api"
	"blog_server/utils"
	"fmt"
	env "github.com/alibabacloud-go/darabonba-env/client"
	dysmsapi "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	console "github.com/alibabacloud-go/tea-console/client"
	util "github.com/alibabacloud-go/tea-utils/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type VerifyCodeRequest struct {
	PhoneNumber string `json:"phone_number"`
}

type VerifyCodeResponse struct {
	PhoneNumber string `json:"phone_number"`
	Code        string `json:"code"`
}

type VerificationCode struct {
	Code        string    `json:"code"`
	ExpiredTime time.Time `json:"expired_time"`
}

var VerficationCodes = make(map[string]VerificationCode)

func SendCode(c *gin.Context) {
	var verifyRequest VerifyCodeRequest

	if err := c.ShouldBindJSON(&verifyRequest); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	client, _err := api.CreateClient(env.GetEnv(tea.String("ACCESS_KEY_ID")), env.GetEnv(tea.String("ACCESS_KEY_SECRET")))
	if _err != nil {
		return
	}
	signName := "阿里云"
	templateCode := "SMS_122310183"
	// 1.发送短信
	sendReq := &dysmsapi.SendSmsRequest{
		PhoneNumbers: &verifyRequest.PhoneNumber,
		SignName:     &signName,
		TemplateCode: &templateCode,
	}

	sendResp, _err := client.SendSms(sendReq)
	if _err != nil {
		return
	}

	code := sendResp.Body.Code
	if !tea.BoolValue(util.EqualString(code, tea.String("OK"))) {
		console.Log(tea.String("错误信息: " + tea.StringValue(sendResp.Body.Message)))
		return
	}

	bizId := sendResp.Body.BizId

	// 2. 查询结果 - 立即查询，无需等待
	queryReq := &dysmsapi.QuerySendDetailsRequest{
		PhoneNumber: util.AssertAsString(verifyRequest.PhoneNumber),
		BizId:       bizId,
		PageSize:    tea.Int64(10),
		CurrentPage: tea.Int64(1),
	}

	queryResp, err := client.QuerySendDetails(queryReq)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to query details"})
		return
	}

	dtos := queryResp.Body.SmsSendDetailDTOs.SmsSendDetailDTO
	if len(dtos) > 0 {
		dto := dtos[0]
		verificationCode := tea.StringValue(dto.OutId)

		// 存储验证码
		VerficationCodes[verifyRequest.PhoneNumber] = VerificationCode{
			Code:        verificationCode,
			ExpiredTime: time.Now().Add(5 * time.Minute),
		}

		c.JSON(http.StatusOK, gin.H{"code": 200, "msg": "Verification code sent"})
	} else {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "No details found for the sent SMS"})
		return
	}
}

func VerifyCode(c *gin.Context) {
	var verifyCode VerifyCodeResponse
	if err := c.ShouldBindJSON(&verifyCode); err != nil {
		utils.Fail(c, nil)
		return
	}

	record, exists := VerficationCodes[verifyCode.PhoneNumber]
	if !exists || time.Now().After(record.ExpiredTime) || record.Code != verifyCode.Code {
		fmt.Println(record.Code)
		fmt.Println(verifyCode.Code)
		utils.Fail(c, nil)
		return
	}

	delete(VerficationCodes, verifyCode.PhoneNumber)
	utils.Success(c, nil)
}
